import socket
import logging
from .__cmd import CmdHandler
from .__epoll import EpollHandler


def create_socket(address, family, type):
    sock = None
    try:
        sock = socket.socket(family, type)
        sock.bind(address)
        sock.listen(10)
    except socket.error, e:
        logger.debug('Create socket failed')
        if not sock:
            sock.close()
        sys.exit(-1)
    logger.debug('Create socket: %d', sock.fileno())
    return sock


def handle_accept(sock):
    conn, addr = sock.accept()
    conn.setblocking(0)
    logger.debug('Peer address: %s', addr)
    __epoll_handler.set_event(conn, handle_read, handle_write, 0)


def handle_read(data):
    logger.debug('data: %s', data)
    cmd_proc(data)


def handle_write():
    logger.debug('output: %s', ''.join(__cmd_handler.output))
    if not len(__cmd_handler.output):
        return None
    return __cmd_handler.output


def create_server(address, family, type):
    sock = create_socket(address, family, type)
    __epoll_handler.set_base_event(sock, handle_accept)


__epoll_handler = EpollHandler()
__cmd_handler = CmdHandler()
logger = logging.getLogger('CliServer')
dispatcher = __epoll_handler.dispatcher
cmd_output = __cmd_handler.cmd_output
cmd_register = __cmd_handler.cmd_register
cmd_proc = __cmd_handler.cmd_proc
